import store from '@/store';
import { deleteToken, readToken } from '@/utils/auth';
import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

//封装  origin 方法
function origin(target, type) {
  // 保存target   ---  type 方法
  const origin = target.prototype[type];
  //增强 方法
  target.prototype[type] = function (location, okCallback, errCallback) {
    if (okCallback || errCallback) {
      return origin.call(this, location, okCallback, errCallback);
    } else {
      return origin.call(this, location).catch(() => {});
    }
  };
}

//增强push方法
origin(VueRouter, 'push');
//增强 replace 方法
origin(VueRouter, 'replace');

import routes from './routes';

//创建路由对象
let router = new VueRouter({
  mode: 'history',
  routes,
  // 1. 刚进入页面，2.，每次切换路由
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { x: 0, y: 0 };
    }
  },
});
let authPath = ['/trade'];
router.beforeEach(async (to, from, next) => {
  const token = readToken();
  if (token) {
    console.log('token存在');
    let { userInfo } = store.state.user;
    if (userInfo.id) {
      console.log('token存在，用户信息存在，直接放行');
      next();
    } else {
      console.log('用户信息不存在，请求 获取用户信息');
      try {
        await store.dispatch('user/asyncGetUserInfo');
        console.log('成功获取到用户信息');
        next();
      } catch (error) {
        console.log(
          '没有获取到用户信息，token失效，  删除本地token,跳转至登录页面，重新登录'
        );
        deleteToken();
        next('/login');
      }
    }
  } else {
    console.log(
      'token 不存在，没有登录，不允许访问 敏感路由【支付，个人中心，订单，收货地址】'
    );
    if (authPath.includes(to.path)) {
      next('/login');
    } else {
      next();
    }
  }
});
export default router;
